/**
 *
 */

package com.guchenbo.example.httpclient;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Cre.Gu
 */
public class HttpClientTest {
    private CloseableHttpClient httpClient;

    @Test
    public void test() {
        httpClient = HttpClients.createDefault();

        final String validationUrl = "https://www.baidu.com";
        HttpRequestBase httpRequest = new HttpGet(validationUrl);

        CloseableHttpResponse httpResponse = null;
        String result = null;
        try {
            httpResponse = httpClient.execute(httpRequest);
            HttpEntity entity = httpResponse.getEntity();

            result = EntityUtils.toString(entity);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpResponse);
        }
    }

    @Test
    public void sinaIndex() {
        String url = "http://m1.mail.sina.cn/mobile/index.php?html5&ver=4.5.15";

        String cookies = "SCF=As-4FstV0cAyqs94LQpLlCWo8H8sEOIdQHUht_-tT3EYrip2jEVl_h8xXrnp0VPkIz9aCLDPuu-0nsEmTCPrMnA.; SUB=_2A250GhkrDeThGedH41oZ9ybPwz6IHXVX5KdjrDV9PUNbktBeLWPFkW2PVcpvZ4GHv_Huy25XD5omodi1FA..; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFefa76wUsPrbZ45UFPO0U55JpX5K2hUgL.Fo241hnRS0n01hz2dJLoIp7LxKML1KBLBKnLxKqL1hnLBoMp1KnR1hMRe0nE; SWEBAPPSESSID=6687e3db7f5faaddd69f8b88c1c664237; SWMHA=usrmdinst_4";

        doHttp(url, 0, null, cookies, null);
    }

    @Test
    public void sinaListMail() {
        String url = "http://m1.mail.sina.cn/wa.php?a=list_mail";
        HeaderModel headerModel = new HeaderModel();

        Map<String, String> params = new HashMap<>();
        params.put("fid", "new");
        params.put("start", "0");
        //        params.put("refid", "0464C7165B3738B15270A6CC6436E9022A00000000000001");
        params.put("order", "htime");
        params.put("sorttype", "desc");
        params.put("length", "20");

        String cookies = "SCF=ApllsrdGCQwyS3uX813NTMQh5BqofGAHi3dOay_LqokjKqCQVQs1byMI9z7DXI5DRJTS54ZL1snyF4PiI8NPlws.; SUB=_2A250Ty8HDeThGedH41oZ9ybPwz6IHXVXs7FPrDV9PUNbktBeLRjZkW0oxlPK_Fp637tJxRNHqjb_ursKGQ..; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFefa76wUsPrbZ45UFPO0U55JpX5K2hUgL.Fo241hnRS0n01hz2dJLoIp7LxKML1KBLBKnLxKqL1hnLBoMp1KnR1hMRe0nE; SWEBAPPSESSID=6b11c8ee5766eecca3ffad1521ee0d75; SWMHA=usrmdinst_4";
        String[] cs = StringUtils.split(cookies, "; ");
        Arrays.stream(cs).forEach(c -> System.out.println(c));
        doHttp(url, 1, params, cookies, null);
    }

    @Test
    public void sinaReadMail() {
        String url = "http://m1.mail.sina.cn/wa.php?a=read_mail";
        HeaderModel headerModel = new HeaderModel();

        Map<String, String> params = new HashMap<>();
        params.put("fid", "new");
        params.put("mid", "04B97A0FFF8DBB5494E0B8BEA7CC3B0F4600000000000001");

        //        String cookies = "SCF=As-4FstV0cAyqs94LQpLlCWo8H8sEOIdQHUht_-tT3EYrip2jEVl_h8xXrnp0VPkIz9aCLDPuu-0nsEmTCPrMnA.; SUB=_2A250GhkrDeThGedH41oZ9ybPwz6IHXVX5KdjrDV9PUNbktBeLWPFkW2PVcpvZ4GHv_Huy25XD5omodi1FA..; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFefa76wUsPrbZ45UFPO0U55JpX5K2hUgL.Fo241hnRS0n01hz2dJLoIp7LxKML1KBLBKnLxKqL1hnLBoMp1KnR1hMRe0nE; SWEBAPPSESSID=6687e3db7f5faaddd69f8b88c1c664237; SWMHA=usrmdinst_4";
        //        String cookies = "SWEBAPPSESSID=673e7afc055c5b569e733e75963b1ae2; SWMHA=usrmdinst_3; SCF=AnkyoDqqjyBxCnKNiTegZdPrR2Mz0TNaKHgdovujCKPqmPjruloRB_KfF4ASyvan0CVtL4NddgbL7OVl_PvCbWY.; SUB=_2A250GuaNDeThGedH41oZ9ybPwz6IHXVX5IrFrDV9PUNbktANLXmlkW1SUsET7JuU-p7nC-ESU3tShS8W4A..; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFefa76wUsPrbZ45UFPO0U55JpX5K2hUgL.Fo241hnRS0n01hz2dJLoIp7LxKML1KBLBKnLxKqL1hnLBoMp1KnR1hMRe0nE";
        String cookies = "SWMHA=usrmdinst_0; SCF=ApllsrdGCQwyS3uX813NTMQh5BqofGAHi3dOay_LqokjABw8NfJU_YRRi7Padgco8n7wnrq6MEcEZhuQfMQkVBQ.; SUB=_2A250Guu8DeThGedH41oZ9ybPwz6IHXVX5PX0rDV9PUNbktBeLVChkW2Qx2VKiSIf6_YFXddpRXngZlLWRg..; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFefa76wUsPrbZ45UFPO0U55JpX5K2hUgL.Fo241hnRS0n01hz2dJLoIp7LxKML1KBLBKnLxKqL1hnLBoMp1KnR1hMRe0nE; SWEBAPPSESSID=6239ed0acb72722bc21ac8a1a4e854ef";

        doHttp(url, 1, params, cookies, null);
    }

    @Test
    public void qqIndex() {
        String url = "https://w.mail.qq.com/cgi-bin/mobile?sid=Gi5FEUzju5eJdmkwXcLT5vNw,4,qQzdhU2RtYnJEWnZNcjNvKm0ybGNKaXI0MUhzakJ4dyo2MmMxOWJiMHZ0MF8.&t=phone#today";

        String cookies = "pgv_pvi=9574167552; pgv_si=s4371513344; RK=nHEvkSNvat; ptcz=3aa29f5ed2ec78850b8de2c853cce3853ef191280a75ef0e05ef15852112a153; wimrefreshrun=0&; qm_domain=https://mail.qq.com; foxacc=523001140&1; qm_loginfrom=523001140&wpt; CCSHOW=000001; webp=1; newpt=2; promote=0; pgv_info=ssid=s4967890068; pgv_pvid=3122053275; o_cookie=523001140; mcookie=0&y; ptisp=ctc; luin=o0523001140; lskey=0001000052726b93fa847ead195c3aa5aa74bc007b3cf5ad010e40eb4bb5c81cb62445c69a9026210cb62de8; pt2gguin=o0523001140; uin=o0523001140; skey=@HJejKtVA8; p_uin=o0523001140; p_skey=C7aSdmbrDZvMr3o*m2lcJir41HsjBxw*62c19bb0vt0_; pt4_token=CgLgrEud14xHmw7xP0T4CLTMuU3F6jrgY6WKzK3Thp0_; p_luin=o0523001140; p_lskey=0004000060dfd877e40c032e0f0b5c2fe58b3449ca4b150d566dd1e320bcba7a8f06ca890e27b832e97e494a; qm_flag=0; qqmail_alias=guchenbo@foxmail.com; msid=Gi5FEUzju5eJdmkwXcLT5vNw,4,qQzdhU2RtYnJEWnZNcjNvKm0ybGNKaXI0MUhzakJ4dyo2MmMxOWJiMHZ0MF8.; sid=523001140&1ac88a4e3433aa7f154e3c7253ce3893,qQzdhU2RtYnJEWnZNcjNvKm0ybGNKaXI0MUhzakJ4dyo2MmMxOWJiMHZ0MF8.; qm_username=523001140; qm_lg=qm_lg; new_mail_num=523001140&0; ssl_edition=sail.qq.com; edition=mail.qq.com; username=523001140&523001140; pcache=6712dd6df24bff8MTQ5Nzc3NTQyMw@523001140@4; mpwd=6712dd6df24bff8MTQ5Nzc3NTQyMw@523001140@4";

        doHttp(url, 0, null, cookies, null);
    }

    @Test
    public void qqListMail() {
        String url = "https://w.mail.qq.com/cgi-bin/mail_list?ef=js&r=0.23777202730348113&sid=Gi5FEUzju5eJdmkwUcXT5vNw,4,qQzdhU2RtYnJEWnZNcjNvKm0ybGNKaXI0MUhzakJ4dyo2MmMxOWJiMHZ0MF8.&t=mobile_data.json&s=list&cursor=max&cursorcount=20&folderid=1&device=android&app=phone&ver=app";

        String cookies = "pgv_pvi=9574167552; pgv_si=s4371513344; RK=nHEvkSNvat; ptcz=3aa29f5ed2ec78850b8de2c853cce3853ef191280a75ef0e05ef15852112a153; wimrefreshrun=0&; qm_domain=https://mail.qq.com; foxacc=523001140&1; qm_loginfrom=523001140&wpt; CCSHOW=000001; webp=1; newpt=2; promote=0; pgv_info=ssid=s4967890068; pgv_pvid=3122053275; o_cookie=523001140; mcookie=0&y; ptisp=ctc; luin=o0523001140; lskey=0001000052726b93fa847ead195c3aa5aa74bc007b3cf5ad010e40eb4bb5c81cb62445c69a9026210cb62de8; pt2gguin=o0523001140; uin=o0523001140; skey=@HJejKtVA8; p_uin=o0523001140; p_skey=C7aSdmbrDZvMr3o*m2lcJir41HsjBxw*62c19bb0vt0_; pt4_token=CgLgrEud14xHmw7xP0T4CLTMuU3F6jrgY6WKzK3Thp0_; p_luin=o0523001140; p_lskey=0004000060dfd877e40c032e0f0b5c2fe58b3449ca4b150d566dd1e320bcba7a8f06ca890e27b832e97e494a; qm_flag=0; qqmail_alias=guchenbo@foxmail.com; msid=Gi5FEUzju5eJdmkwXcLT5vNw,4,qQzdhU2RtYnJEWnZNcjNvKm0ybGNKaXI0MUhzakJ4dyo2MmMxOWJiMHZ0MF8.; sid=523001140&1ac88a4e3433aa7f154e3c7253ce3893,qQzdhU2RtYnJEWnZNcjNvKm0ybGNKaXI0MUhzakJ4dyo2MmMxOWJiMHZ0MF8.; qm_username=523001140; qm_lg=qm_lg; new_mail_num=523001140&0; ssl_edition=sail.qq.com; edition=mail.qq.com; username=523001140&523001140; pcache=6712dd6df24bff8MTQ5Nzc3NTQyMw@523001140@4; mpwd=6712dd6df24bff8MTQ5Nzc3NTQyMw@523001140@4";

        doHttp(url, 0, null, cookies, null);
    }

    @Test
    public void qqReadMail() {
        String url = "https://w.mail.qq.com/cgi-bin/readmail?ef=js&r=0.49055055319444074&sid=Gi5FEUzju5eJdmkwUcXT5vNw,4,qQzdhU2RtYnJEWnZNcjNvKm0ybGNKaXI0MUhzakJ4dyo2MmMxOWJiMHZ0MF8.&t=mobile_data.json&s=read&showreplyhead=1&disptype=html&mailid=ZC4616-Y1fEpPkQ6MTec2w1XUl3a75";
        String cookies = "pgv_pvi=9574167552; pgv_si=s4371513344; RK=nHEvkSNvat; ptcz=3aa29f5ed2ec78850b8de2c853cce3853ef191280a75ef0e05ef15852112a153; wimrefreshrun=0&; qm_domain=https://mail.qq.com; foxacc=523001140&1; qm_loginfrom=523001140&wpt; CCSHOW=000001; webp=1; newpt=2; promote=0; pgv_info=ssid=s4967890068; pgv_pvid=3122053275; o_cookie=523001140; mcookie=0&y; ptisp=ctc; luin=o0523001140; lskey=0001000052726b93fa847ead195c3aa5aa74bc007b3cf5ad010e40eb4bb5c81cb62445c69a9026210cb62de8; pt2gguin=o0523001140; uin=o0523001140; skey=@HJejKtVA8; p_uin=o0523001140; p_skey=C7aSdmbrDZvMr3o*m2lcJir41HsjBxw*62c19bb0vt0_; pt4_token=CgLgrEud14xHmw7xP0T4CLTMuU3F6jrgY6WKzK3Thp0_; p_luin=o0523001140; p_lskey=0004000060dfd877e40c032e0f0b5c2fe58b3449ca4b150d566dd1e320bcba7a8f06ca890e27b832e97e494a; qm_flag=0; qqmail_alias=guchenbo@foxmail.com; msid=Gi5FEUzju5eJdmkwXcLT5vNw,4,qQzdhU2RtYnJEWnZNcjNvKm0ybGNKaXI0MUhzakJ4dyo2MmMxOWJiMHZ0MF8.; sid=523001140&1ac88a4e3433aa7f154e3c7253ce3893,qQzdhU2RtYnJEWnZNcjNvKm0ybGNKaXI0MUhzakJ4dyo2MmMxOWJiMHZ0MF8.; qm_username=523001140; qm_lg=qm_lg; new_mail_num=523001140&0; ssl_edition=sail.qq.com; edition=mail.qq.com; username=523001140&523001140; pcache=6712dd6df24bff8MTQ5Nzc3NTQyMw@523001140@4; mpwd=6712dd6df24bff8MTQ5Nzc3NTQyMw@523001140@4";

        doHttp(url, 1, null, cookies, null);
    }

    @Test
    public void testTaobao() {
        String url = "https://trade.tmall.com/detail/orderDetail.htm?spm=a1z09.2.0.0.OMlSCH&bizOrderId=26138491305192895";
        String cookies = "cq=ccp%3D0; hng=; l=AkNDs-367W59m0vYWzFWdfxRUw3t7df6; _tb_token_=e7ee31be665e; uc1=cookie14=UoW%2BsOCCr3A0nw%3D%3D&lng=zh_CN&cookie16=UIHiLt3xCS3yM2h4eKHS9lpEOw%3D%3D&existShop=false&cym=1&cookie21=Vq8l%2BKCLiv0Mzbofagu7Fg%3D%3D&tag=8&cookie15=UtASsssmOIJ0bQ%3D%3D&pas=0; uc3=sg2=B0ABf6NRtv42g%2FgZNFtGOPvu%2Btll9usdhiLcFpqcjUk%3D&nk2=BIOdpFmH&id2=UojQOJ7dAdGq&vt3=F8dBzWCvyLBwd5q%2FMPM%3D&lg2=Vq8l%2BKCLz3%2F65A%3D%3D; uss=WvZsEnT3SXiofxhPlKwO91P6GmO8HtTmwStyl4dGm1hV1kzsw%2BbqSqducQ%3D%3D; lgc=gutiti; tracknick=gutiti; cookie2=1cb6011aa0b1398841faf99b65b89416; sg=i88; cookie1=AnCCxMZw8zgeftxKx5r3cgdP97Z47Y6sCKIvEqU1ucA%3D; unb=194199528; t=f893c324deef2676b5b0288d43d36317; _l_g_=Ug%3D%3D; _nk_=gutiti; cookie17=UojQOJ7dAdGq; login=true; ucn=unsz; cna=UpWREdhlflQCAXudmYLO4AzQ; isg=Atvb7sbxBimlTnoAhTrwVzE7ajlPieyLKcKNB80Yt1rxrPuOVYB_AvmuMDvY";

        doHttp(url, 0, null, cookies, null);
    }

    public static HttpUriRequest buildRequest(String url, int type, Map<String, String> params, String cookies) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpRequestBase httpRequest = null;

        if (type == 1) {
            httpRequest = new HttpPost(url);
        } else {
            httpRequest = new HttpGet(url);
        }

        CloseableHttpResponse httpResponse = null;

        if (type == 1 && params != null) {
            List<NameValuePair> nvps = HttpUtils.setParams(params);
            try {
                ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(nvps));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        //            setHeader(httpRequest, headerModel);
        httpRequest.setHeader("Cookie", cookies);
        httpRequest.setHeader("User-Agent",
                        "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2 like Mac OS X) AppleWebKit/602.3.12 (KHTML, like Gecko) Mobile/14C92");
        //            httpRequest.setHeader("accept", "application/json, text/javascript, */*; q=0.01");
        //            httpRequest.setHeader("x-requested-with", "XMLHttpRequest");
        //            httpRequest.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");

        //        httpRequest.setHeader("Host", "ebill.spdbccc.com.cn");
        //        httpRequest.setHeader("Referer", "http://mail.163.com/js6/read/readhtml.jsp?mid=25:1tbiGREtC1XlZRmzWgAAsL&font=15&color=064977\n");
        //                    httpRequest.setHeader("origin","https://buyertrade.taobao.com");
        //        httpRequest.setHeader("referer",
        //                        "http://mail.163.com/js6/main.jsp?sid=MCtGIJKnldeJOheKelnncQifIZaLaqIn&df=mail163_letter");
        //
        //            httpRequest.setHeader(":authority","buyertrade.taobao.com");
        //            httpRequest.setHeader(":method","POST");
        //            httpRequest.setHeader(":path","/trade/itemlist/asyncBought.htm?action=itemlist/BoughtQueryAction&event_submit_do_query=1&_input_charset=utf8");
        //            httpRequest.setHeader(":scheme","https");

        return httpRequest;
    }

    public static String doRequest(HttpUriRequest request) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = null;
        try {
            response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        return result;
    }

    public static String doHttp(String url, int type, Map<String, String> params, String cookies, String noEncoded) {
        String result = null;
        CloseableHttpClient httpClient = null;

        try {

            httpClient = HttpClients.custom().setSSLHostnameVerifier((s1, s2) -> true).build();
        } catch (Exception e) {
            e.printStackTrace();
        }

        HttpRequestBase httpRequest = null;

        if (type == 1) {
            httpRequest = new HttpPost(url);
        } else {
            httpRequest = new HttpGet(url);
        }

        CloseableHttpResponse httpResponse = null;
        try {

            if (type == 1) {
                if (params != null) {
                    List<NameValuePair> nvps = HttpUtils.setParams(params);
                    ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(nvps));
                }
                if (noEncoded != null) {
                    ((HttpPost) httpRequest)
                                    .setEntity(new StringEntity(noEncoded, ContentType.APPLICATION_FORM_URLENCODED));
                }

            }

            httpRequest.setHeader("PARAM-TASK-RETRY", "" + 2);

                httpRequest.setHeader("PARAM-TASK-ID","TASKEB000101201708081911540031300002");
            httpRequest.setHeader("PARAM-CHANNEL-TYPE", "EB");
            httpRequest.setHeader("PARAM-CHANNEL-CODE", "000101");
            httpRequest.setHeader("PARAM-REQUEST-TIMEOUT", "" + 60);

            httpRequest.setHeader("Accept", "*/*");


            //            setHeader(httpRequest, headerModel);
            httpRequest.setHeader("Cookie", cookies);
//            httpRequest.setHeader("User-Agent",
//                            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");
            //                            "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2 like Mac OS X) AppleWebKit/602.3.12 (KHTML, like Gecko) Mobile/14C92");
            //            httpRequest.setHeader("accept", "application/json, text/javascript, */*; q=0.01");
            //            httpRequest.setHeader("x-requested-with", "XMLHttpRequest");
            //            httpRequest.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");

//                                    httpRequest.setHeader("Host","ebill.spdbccc.com.cn");
//                                    httpRequest.setHeader("Origin","https://ebill.spdbccc.com.cn");
//                        httpRequest.setHeader("Referer",


//
//                                        "https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/toLogin.action?zrz4ofa8h5IFb1udd/JAcqNEAmH7MXdciqgKNtpABZfFoJ9bzOfHz3vKDGBNSNi/kwvwEjRFNfkap$R69TPJZ5rXykbjsC0uz452olT$/n/87rD7x0UkODGghykTvpLMgwPoqhCl3kY1kcpt5XwrMA==");
            //
            //            httpRequest.setHeader(":authority","buyertrade.taobao.com");
            //            httpRequest.setHeader(":method","POST");
            //            httpRequest.setHeader(":path","/trade/itemlist/asyncBought.htm?action=itemlist/BoughtQueryAction&event_submit_do_query=1&_input_charset=utf8");
            //            httpRequest.setHeader(":scheme","https");

            httpResponse = httpClient.execute(httpRequest);
            System.out.println(httpResponse.getStatusLine());
            Header[] headers = httpResponse.getAllHeaders();
            for (Header header : headers) {
//                                System.out.println(header.getName()+": "+header.getValue());
            }

            HttpEntity entity = httpResponse.getEntity();

            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpResponse);
        }
        System.out.println(result);
        return result;
    }


    class Email126 {

    }
}
